<template>
  <el-form ref="form" :model="form" label-width="120px">
    <!-- 地权联动组件 -->
    <el-row>
      <el-select v-model="form.province" placeholder="请选择省" @change="changePro" class="item">
        <el-option v-for="item in addressData" :key="item.code" :label="item.name" :value="item.name">
        </el-option>
      </el-select>
      <el-select v-model="form.city" placeholder="请选择市" @change="changeCity" class="item">
        <el-option v-for="item in cityData" :key="item.code" :label="item.name" :value="item.name">
        </el-option>
      </el-select>
      <el-select v-model="form.district" placeholder="请选择区" @change="changeArea" class="item">
        <el-option v-for="item in areaData" :key="item.code" :label="item.name" :value="item.name">
        </el-option>
      </el-select>
    </el-row>
    <!-- <h3>测试当前选中地址：{{ result }}</h3> -->
  </el-form>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import address from "@/utils/address.json"; //全国省市区街道数据

// 省数据
const addressData = ref([]);
// 市数据
const cityData = ref([]);
// 区数据
const areaData = ref([]);

// 定义props
const props = defineProps({
  form: {
    province: "",
    city: "",
    district: "",
  }
});

// 省份数据初始化
addressData.value = address;

if (props.form.province != "") {
  const city = addressData.value.find(item => item.name === props.form.province);
  if (city) {
    cityData.value = city.children;

    const area = cityData.value.find(item => item.name === props.form.city);
    if (area) {
      areaData.value = area.children;
    }
  }
}

// 方法定义
const reset = () => {
  props.form.province = "";
  props.form.city = "";
  props.form.district = "";
};

const changePro = (e) => {
  const selectedProvince = addressData.value.find(item => item.name === e);
  if (selectedProvince) {
    cityData.value = selectedProvince.children;
    areaData.value = cityData.value[0].children;
    props.form.city = cityData.value[0].name;
    props.form.district = areaData.value[0].name;
  }
};

const changeCity = (e) => {
  const selectedCity = cityData.value.find(item => item.name === e);
  if (selectedCity) {
    areaData.value = selectedCity.children;
    props.form.district = areaData.value[0].name;
  }
};

const changeArea = (e) => {
  const selectedArea = areaData.value.find(item => item.name === e);
  if (selectedArea) {
    props.form.regionalNumber = selectedArea.code;
    props.form.jdData = selectedArea.children;
  }
};

const result = computed(() => {
  if (!props.form.district) return '';
  if (props.form.district) {
    return `${props.form.province}, ${props.form.city}, ${props.form.district}`;
  }
  return `${props.form.province}, ${props.form.city}, ${props.form.district}`;
});
</script>

<style lang="scss" scoped>
.el-row {
  display: inline-flex;
  flex: auto;

  .el-select {
    margin: 0 20px 0 0;
    width: 122px;
  }
}

.item {
  width: 170px !important;
}
</style>